import React, { useState, useRef } from 'react';
import { ProTable, PageContainer, ProForm, ProFormText, ProFormSelect, Search } from '@ant-design/pro-components';
import { Drawer, Button, message, Popconfirm } from 'antd';
import { fetchSeoList, createSeo, updateSeo, deleteSeo } from '@/services/ant-design-pro/seo';

const SeoList = () => {
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState(null);
  const [form] = ProForm.useForm();
  const actionRef = useRef();
  const [activeKey, setActiveKey] = useState<string>('1');
  const handleEdit = (record) => {
    setCurrentRecord(record);
    form.setFieldsValue(record);
    setDrawerVisible(true);
  };

  const handleAdd = () => {
    setCurrentRecord(null);
    form.resetFields();
    setDrawerVisible(true);
  };

  const handleFinish = async (values) => {
    try {
      if (currentRecord) {
        // 编辑
        const response = await updateSeo({ ...currentRecord, ...values });
        if (response.code === '1') {
          message.success('修改成功');
          actionRef.current?.reload();
        } else {
          message.error(response.msg);
        }
      } else {
        // 添加
        const response = await createSeo({...values,type:activeKey});
        if (response.code === '1') {
          message.success('添加成功');
          actionRef.current?.reload();
        } else {
          message.error(response.msg);
        }
      }
    } catch (error) {
      message.error('操作失败');
    } finally {
      setDrawerVisible(false);
    }
  };

  const handleDelete = async (id) => {
    try {
      const response = await deleteSeo({ id });
      if (response.code === '1') {
        message.success('删除成功');
        actionRef.current?.reload();
      } else {
        message.error(response.msg);
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  const columns = [
    {
      title: '页面名称',
      dataIndex: 'title',
      search: false,
      render: (text, record) => <a onClick={() => handleEdit(record)}>{text}</a>,
    },
    {
      title: 'SEO 描述',
      dataIndex: 'description',
      search: false,
    },
    {
      title: 'SEO 关键词',
      dataIndex: 'keywords',
      search: false,
    },
    {
      title: '类型',
      dataIndex: 'type',
      filters: true,
      search:false,
      hidden: true
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      render: (_, record) => [
        <a key="edit" onClick={() => handleEdit(record)}>
          编辑
        </a>,
         <Popconfirm
         key="delete"
         title="确定删除该数据吗？"
         onConfirm={() => handleDelete(record.id)}
       >
        <a key="delete">
          删除
        </a>
        </Popconfirm>
      ],
    },
  ];

  return (
    <PageContainer header={{title:''}}>
      <ProTable
        columns={columns}
        search={false}
        rowKey="id"
        request={async (params) => {
          return fetchSeoList({...params,type:activeKey});
        }}
        toolbar={
           {
            menu: {
                type: 'tab',
                activeKey: activeKey,
                items: [
                    {
                        key: '1',
                        label: <span>首页</span>,
                    },
                    {
                        key: '2',
                        label: <span>API</span>,
                    },
                    {
                        key: '3',
                        label: <span>关于我们</span>,
                    },
                    {
                        key: '4',
                        label: <span>新闻中心</span>,
                    },
                    {
                        key: '5',
                        label: <span>数据API技术相关</span>,
                    },
                    {
                      key: '6',
                      label: <span>API接口文档相关</span>,
                  },
                  {
                    key: '7',
                    label: <span>售后及商务问题模板</span>,
                },
                {
                  key: '8',
                  label: <span>行业资讯</span>,
              },
                ],
                onChange: (key) => {
                    setActiveKey(key as string);
                    actionRef.current?.reloadAndRest();
                },
            }
           }
        }
        actionRef={actionRef}
        toolBarRender={() => [
          // <Button key="add" type="primary" onClick={handleAdd}>
          //   新增 SEO
          // </Button>,
        ]}
      />
      <Drawer
        title={currentRecord ? '编辑 SEO' : '新增 SEO'}
        width={400}
        onClose={() => setDrawerVisible(false)}
        open={drawerVisible}
        bodyStyle={{ paddingBottom: 80 }}
      >
        <ProForm
          form={form}
          onFinish={handleFinish}
          initialValues={currentRecord || {}}
          submitter={{
            resetButtonProps: {
              style: { display: 'none' }, 
            },
          }}
        >
          <ProFormText
            name="title"
            label="SEO标题"
            placeholder="请输标题"
            rules={[{ required: true, message: '标题不能为空' }]}
          />
          <ProFormText
            name="description"
            label="SEO描述"
            placeholder="请输入描述"
          />
          <ProFormText
            name="keywords"
            label="SEO关键词"
            placeholder="请输入关键词"
          />
        </ProForm>
      </Drawer>
    </PageContainer>
  );
};

export default SeoList;
